#ifndef COMMON_HEADER
#define COMMON_HEADER

#define bool char
#define true 1
#define false 0

#include <WinSock2.h>
#include <process.h>
#include <windows.h>

#define MAXBUFFSIZE 4096
#define MAXCONN 30
#define MAX_SEM_COUNT 1000
#define STACKSIZE 1000

#define MAXSERVERS 4

#define VICE_PORT 9876
#define TESTER 0
#define PLNODE 1

#define LOCALHOST "127.0.0.1"

#define ADD_PINODE_SUCCESS 0
#define ADD_PINODE_FAIL 1

#define CLOSE_PINODE 2

#define CONNECT_REQUEST 3
#define DELETE_REQUEST 4
#define GETPNODEBYUSER 5
#define GETUSERNUMBYPNODE 6

#define PINODE_QUIT 7
#define PINODE_JOIN 8
#define SYSCTRL_QUIT 9

#define MYERROR 100

#define YES 200
#define NO 201

#define SYS_HELLO 300
#define SYS_BACKUP 301

#define MAX_TODO_TASK 1000
#define SERVER_LIST_FILE "server_list.txt"

typedef struct _TOperationInfo {
	int op;
	int val;
} TOperationInfo;

typedef struct _Task {
	TOperationInfo info;
	int id;
	struct _Task* next;
} Task;

typedef struct _TSocketInfo {
	WSAOVERLAPPED overlapped;
	ULONG recvBytes;
	ULONG flag;
	WSABUF buf;
	char internalBuffer[MAXBUFFSIZE];
} TSocketInfo;

typedef int KEYTYPE;

typedef struct _TUserList {
	KEYTYPE id;
	struct _TUserList *next;
} TUserList;

typedef struct _TUserInfo {
	KEYTYPE id;
	void* param;
	struct _TUserInfo* father;
	struct _TUserInfo* left;
	struct _TUserInfo* right;
} TUserInfo;

typedef struct _Network_Node_Info {
	int id;
	char addr[10];
	unsigned short commPort;
	unsigned short bakcupPort;
	unsigned short testPort;
	unsigned short serverPort;
	unsigned short registerPort;
	
} Network_Node_Info;

Network_Node_Info serverList[MAXSERVERS];
int SERVER_LIST_SIZE;

TUserInfo* tUserInfo(KEYTYPE id);
TSocketInfo* tSocketInfo(void);

void startUpNetwork();
SOCKET createListenSocket(unsigned short port);
SOCKET createConnectSocket(unsigned short port, char* ipaddr);
SOCKET createServerConnectSocket(char* ipaddr);
SOCKET createTesterConnectSocket(char *ipaddr);
SOCKET createListenSocket2(unsigned short port, int *retV);
bool testSocket(SOCKET sock);

void getList(void);
bool addUser(TUserInfo* root, KEYTYPE id, TUserInfo** rootUser);
bool deleteUser(TUserInfo* root, KEYTYPE id, TUserInfo** rootUser);
bool find(TUserInfo* root, KEYTYPE id, TUserInfo** rootUser);
void getAllUsers(TUserInfo* rootUser, KEYTYPE *retArray);

#endif